#include <QtGui>

#include "controlpanel.h"
#include <stdio.h>

ControlPanel::ControlPanel(QWidget *parent, Grid *grid) :
    QWidget(parent)
{
    ui.setupUi(this);

    QDesktopWidget *pDesktop = QApplication::desktop();
    for (int s = 0; s < pDesktop->screenCount(); s++)
    {
        ui.displayNum->addItem(QString("%1").arg(s));
    }

    ui.resolution->addItem("640x480");
    ui.resolution->addItem("800x600");
    ui.resolution->addItem("1024x768");
    ui.resolution->addItem("1280x960");
    ui.resolution->setCurrentIndex(1);

    mothership = grid;

    gridWidthChanged();
    gridDimsChanged();
    framesChanged();
    coverageChanged();
}

void ControlPanel::gridWidthChanged()
{
    // Validate new input
    bool ok = false;
    int newSize = ui.gridWidth->text().toInt(&ok);
    if (!ok)
    {
        return;
    }
    else
    {
        mothership->gridWidth = newSize;
        mothership->updateSquares();
    }
}

void ControlPanel::gridDimsChanged()
{
    // Update the info panel
    ui.gridDimensions->setText(QString("%1 X %2 = %3 (%4 X %5 px)").arg(mothership->gridSize[0])
                                                                      .arg(mothership->gridSize[1])
                                                                      .arg(mothership->gridSize[0] * mothership->gridSize[1])
                                                                      .arg(mothership->geometry[2])
                                                                      .arg(mothership->geometry[3]));
}

void ControlPanel::framesChanged()
{
    float preStimTime = ui.prestimFrames->text().toFloat() / ui.framerate->text().toFloat() * 1000.0;
    float stimTime = ui.stimFrames->text().toFloat() / ui.framerate->text().toFloat() * 1000.0;
    float postStimTime = ui.poststimFrames->text().toFloat() / ui.framerate->text().toFloat() * 1000.0;

    float totalTime = ui.nStimuli->text().toFloat() * (preStimTime + stimTime + postStimTime);

    ui.trialTime->setText(QString("%1 / %2 / %3 ms").arg(preStimTime, 0, 'f', 3)
                                                    .arg(stimTime, 0, 'f', 3)
                                                    .arg(postStimTime, 0, 'f', 3));
    if (totalTime < 1000)
    {
        ui.totalTime->setText(QString("%1 ms").arg(totalTime, 0, 'f', 3));
    } else
    {
        ui.totalTime->setText(QString("%1 s").arg(totalTime/1000, 0, 'f', 3));
    }
}

void ControlPanel::coverageChanged()
{
    float pActive = ui.nSpots->text().toFloat() / (mothership->gridSize[0] * mothership->gridSize[1]);
    float avgCoverage = pActive * ui.nStimuli->text().toFloat();

    ui.proportionActive->setText(QString("%1").arg(pActive, 0, 'f', 3));
    ui.avgCoverage->setText(QString("%1").arg(avgCoverage, 0, 'f', 3));
}
